package com.demo.widget.meis;

import com.demo.widget.BaseAbility;
import com.demo.widget.ResourceTable;
import com.meis.widget.mobike.MoBikeView;
import com.meis.widget.utils.PixelUtil;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.components.StackLayout;
import ohos.agp.utils.LayoutAlignment;
import ohos.sensor.agent.CategoryMotionAgent;
import ohos.sensor.agent.SensorAgent;
import ohos.sensor.bean.CategoryMotion;
import ohos.sensor.bean.SensorBase;
import ohos.sensor.data.CategoryMotionData;
import ohos.sensor.listener.ICategoryMotionDataCallback;

/**
 * Created by wenshi on 2018/6/8.
 * Description
 */
public class MeiMoBikeAbility extends BaseAbility implements ICategoryMotionDataCallback {
    private MoBikeView mMobikeView;
    private SensorAgent mSensorManager;
    private SensorBase mSensor;
    private int[] mImgs = {
            ResourceTable.Media_ic_share_fb,
            ResourceTable.Media_ic_share_kongjian,
            ResourceTable.Media_ic_share_pyq,
            ResourceTable.Media_ic_share_qq,
            ResourceTable.Media_ic_share_tw,
            ResourceTable.Media_ic_share_wechat,
            ResourceTable.Media_ic_share_weibo
    };

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_mei_mobike_ability);
        PixelUtil.initContext(this);
        mMobikeView = (MoBikeView) findComponentById(ResourceTable.Id_mo_bike);
        mSensorManager = new CategoryMotionAgent();
        mSensor = mSensorManager.getSingleSensor(CategoryMotion.SENSOR_TYPE_GRAVITY);
        addViews();
        mMobikeView.setClickedListener(component -> mMobikeView.onRandomChanged());
    }

    @Override
    protected void onActive() {
        super.onActive();
        mSensorManager.setSensorDataCallback(this, mSensor, SensorAgent.SENSOR_SAMPLING_RATE_UI);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mSensorManager.releaseSensorDataCallback(this);
    }

    private void addViews() {
        int wrapcontent = StackLayout.LayoutConfig.MATCH_CONTENT;
        StackLayout.LayoutConfig lp = new StackLayout.LayoutConfig(wrapcontent, wrapcontent);
        lp.alignment = LayoutAlignment.CENTER;
        for (int i = 0; i < mImgs.length; i++) {
            Image iv = new Image(this);
            iv.setPixelMap(mImgs[i]);
            mMobikeView.addComponent(iv);
        }
    }

    @Override
    public void onSensorDataModified(CategoryMotionData categoryMotionData) {
        float x = categoryMotionData.getValues()[0];
        float y = categoryMotionData.getValues()[1] * 2.0f;
        mMobikeView.onSensorChanged(-x, y);
    }

    @Override
    public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {

    }

    @Override
    public void onCommandCompleted(CategoryMotion categoryMotion) {
    }
}
